// 注册模块别名
require('module-alias/register');

const express = require('express');
const { engine } = require('./util/liquid');
const path = require('path');
const tags = require('./tags');
const filters = require('./filters');
var routers = require('./router');
var { port } = require('./config');
var cookieParser = require('cookie-parser');
const app = express();
// 配置 cors 这个中间件
const cors = require('cors');
const injectLivereload = require('./middleware/injectLivereload');
const { globalCache } = require('@app/util/memoryCache');
const { createProxyMiddleware } = require('http-proxy-middleware');

process.on('uncaughtException', (err) => {
  console.error('捕获到未处理的异常:', err);
});

// 监听未处理的 Promise 拒绝
process.on('unhandledRejection', (reason) => {
  console.error('捕获到未处理的 Promise 拒绝:', reason);
});
tags(engine);
filters(engine);

app.use(injectLivereload);
app.use(cookieParser());
app.use(cors());
app.engine('liquid', engine.express()); // register liquid engine
app.set('views', ['./']); // specify the views directory
app.set('view engine', 'liquid'); // set to default
app.use('/theme', express.static(path.join(__dirname, '../src/theme')));
app.use('/', routers);
// 代理中间件配置 - 支持动态域名获取
app.use(
  '/homeapi',
  createProxyMiddleware({
    target: 'https://default20.oemsaas.cn',
    changeOrigin: true,
    onError: (err, req, res) => {
      console.error('代理错误:', err.message);
      res.status(500).json({
        error: '代理请求失败',
        message: err.message,
        target: globalCache.get('global_current_domain') || '未设置目标地址',
      });
    },
    timeout: 30000,
    proxyTimeout: 30000,
    router: async () => {
      let target = globalCache.get('global_current_domain');
      console.log('当前域名:', target);
      return 'https://' + target ;
    },
  })
);
app.use(
  '/app-api',
  createProxyMiddleware({
    target: 'https://default20.oemsaas.cn',
    changeOrigin: true,
    onError: (err, req, res) => {
      console.error('代理错误:', err.message);
      res.status(500).json({
        error: '代理请求失败',
        message: err.message,
        target: globalCache.get('global_current_domain') || '未设置目标地址',
      });
    },
    timeout: 30000,
    proxyTimeout: 30000,
    router: async () => {
      let target = globalCache.get('global_current_domain');
      console.log('当前域名:', target);
      return 'https://' + target ;
    },
  })
);

app.use(
  '/checkouts-paypal/restapi-VY2P5BTB/ecinlinepay',
  createProxyMiddleware({
    target: 'https://xiaoyuer0999.oemsaas.cn',
    changeOrigin: true,
    onError: (err, req, res) => {
      console.error('代理错误:', err.message);
      res.status(500).json({
        error: '代理请求失败',
        message: err.message,
        target: globalCache.get('global_current_domain') || '未设置目标地址',
      });
    },
    timeout: 30000,
    proxyTimeout: 30000,
    router: async () => {
      console.log('当前域名:https://xiaoyuer0999.oemsaas.');

      return 'https://xiaoyuer0999.oemsaas.cn';
    },
  })
);
app.listen(port, function () {
  console.log(`localhost:${port}`);
});
